<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="板卡" prop="boardId">
       <el-select v-model="queryParams.boardId"  clearable style="width: 240px">
                <el-option v-for="(item, index) in boardIdOptions" :key="index" :label="item.label"
            :value="item.value" :disabled="item.disabled" ></el-option>
          </el-select>
      </el-form-item> -->
      <el-form-item label="直播频道" prop="boardId">
        <el-radio-group v-model="queryParams.boardId"  size="medium" @change="handleRadioChange">
          <el-radio v-for="(item, index) in boardIdOptions" :key="index" :label="item.value"
            :disabled="item.disabled"   >{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button> -->
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:channel:add']"
        >新增自办节目</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
      <el-table-column label="频道号" align="center" prop="channelIdStr" />
      <el-table-column label="板卡" align="center" prop="boardStr" />
      <el-table-column label="频道名称" align="center" prop="name" />
      <el-table-column label="播放地址" align="center" prop="playUrl" />
      <el-table-column label="序号" align="center" prop="number" />
      <el-table-column label="频率" align="center" prop="freq" />
      <el-table-column label="源输出方式" align="center" prop="sourceOut" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_channel_source_out" :value="scope.row.sourceOut"/>
        </template>
      </el-table-column>
       <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"  v-if="scope.row.boardId === -1"
            v-hasPermi="['system:channel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:channel:remove']"  v-if="scope.row.boardId === -1"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

     <!-- 添加或修改自办节目对话框 -->
     <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入频道名称" />
        </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="输出方式" prop="sourceOut">
          <el-select v-model="form.sourceOut">
            <el-option v-for="(item, index) in sourceOutOptions" :key="index" :label="item.label"
            :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>
            </el-col>
        <el-col :span="12">
        <el-form-item label="地址来源" prop="urlType" >
          <el-select v-model="form.urlType" @change="checkUsbExist">
            <el-option v-for="(item, index) in urlTypeOptions" :key="index" :label="item.label"
            :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>

      </el-col>
        </el-row>
        <!-- -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="源文件" v-if="form.urlType === '1'" prop="sourcePath">
          <!-- <el-tree
      style="max-width: 600px"
      :data="treeData"
      :props="treeProps"
      :load="loadNode"
      lazy
       @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      :highlight-current="true"  v-model="form.sourcePath"
      ref="tree"
    ></el-tree> -->
    <el-tree
     node-key="id"
      style="max-width: 600px"
      :data="treeData"
        :load="loadNode"
      :props="treeProps"
      show-checkbox 
      lazy
        @check="handleCheck"
      :highlight-current="true"  
      ref="tree"
    ></el-tree>
        </el-form-item>
        <el-form-item label="节目地址" prop="sourceUrl" v-if="form.urlType === '2'">
          <el-input v-model="form.sourceUrl" placeholder="请输入自办节目的源地址" />
        </el-form-item>
        </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChannel, getChannel, delChannel, addChannel, updateChannel,changeChannelStatus } from "@/api/system/channel";
import { checkUsb,getFileData,getFileDataByPath,getContentType,getContentTypeData } from '@/api/index';


export default {
  name: "Channel",
  dicts: ['sys_channel_type_name', 'sys_user_sex','sys_board_data','sys_channel_source_out','sys_normal_disable'],
  data() {
    return {
      boardIdOptions: [{
        "label": "直播板卡1",
        "value": "1"
      }, {
        "label": "直播板卡2",
        "value": "2"
      }, {
        "label": "自办节目",
        "value": "-1"
      }],
      urlTypeOptions: [{
        "label": "U盘",
        "value": "1"
      }, {
        "label": "网络",
        "value": "2"
      }],
      sourceOutOptions: [{
        "label": "原样输出",
        "value": "none"
      },{
        "label": "HLS格式",
        "value": "hls"
      }],
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
      },
      selectedNode: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 频道管理表格数据
      channelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceUrl: null,
        name: null,
        ip: null,
        port: null,
        status: null,
        path: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "频道名称不能为空", trigger: "blur" }
        ],
        sourceOut: [
          { required: true, message: "源输出方式不能为空", trigger: "blur" }
        ],
        urlType:[
        { required: true, message: "地址来源不能为空", trigger: "blur" }
        ],
        sourceUrl: [
          { required: true, message: "自办节目输入源的地址不能为空", trigger: "blur" }
        ],
        // sourcePath: [
        //   { required: true, message: "请选择源文件", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    // this.queryParams.boardId = '1';
    this.getList();
  },
  watch: {
    'open'(newVal) {
      if(newVal) {  // 弹窗显示时触发
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([]);
          this.form.sourcePath = '';
        });
      }
    }
  },
  methods: {
    handleRadioChange(){
      this.handleQuery();
    },
    loadNode(node, resolve) {
      console.log("loadNode: "+node+"============"+node.level);
      //获取内容分类配置和剧情类型详情
      if (node.level === 0) {
        // 根节点请求后端获取数据
        getFileData().then(response => {
          resolve(response.data);
        },500);
      } else {
        console.log("模拟数据");
        const selectedNodeResultData = node.data;
        console.log("selectedNodeResultData: "+JSON.stringify(selectedNodeResultData));
        if (selectedNodeResultData &&!selectedNodeResultData.leaf) {
          const path = selectedNodeResultData.path;
          console.log("path: "+path);
          getFileDataByPath(path).then(response => {
            const children = response.data;
            resolve(children);
          },500);
        } else {
          resolve([]);
        }
      }
    },
    handleCheckChange(data, checked, indeterminate) {
          console.log("是否有变:"+checked+"=============="+indeterminate);
          console.log("是否有变:----------"+JSON.stringify(data));
          if(checked){
 

          }else{
            this.$refs.tree.setCheckedKeys([]); 
          }
      },
    handleCheck(nodeData, checked) {
      console.log("handleCheck-----------"+JSON.stringify(nodeData)+"=====handleCheck======="+JSON.stringify(checked));
      if (checked) {
        this.$refs.tree.setCheckedKeys([nodeData.id]); // 只保留当前选中节点
        this.form.sourcePath = nodeData.path;
        console.log("不清空");
      }else{
        console.log("===========清空");
        this.$refs.tree.setCheckedKeys([]);  
      }
    },
    /** 查询频道管理列表 */
    getList() {
      this.loading = true;
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sourceUrl: null,
        sourceOut: "none",
        sourcePath: null,
        name: null,
        ip: null,
        port: null,
        status: null,
        path: null,
        urlType: "1",
      };
      this.resetForm("form");
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自办节目";
      this.checkUsbExist();
      // this.loadNode();
    },
    checkUsbExist(){
      if(this.form.urlType === "1"){
        checkUsb().then(response => {
        console.log('请求成功:', JSON.stringify(response));
        // 处理响应数据
        var data = response.data;
        console.log("校验USB是否挂载"+JSON.stringify(response));
        if(!data){
          //不存在USB文件
          // this.$message.error(response.msg+"=============");
          this.$modal.alertError(response.msg);
          return;
        }
      })
      }
      console.log("=========校验USB盘是否挂载==="+this.form.urlType);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      var boardId = row.boardId;
      console.log("修改:"+boardId);
      if(boardId != -1){
        this.$message.error('非自办节目,不允许进行修改');
        return;
      }
      console.log("修改频道:"+JSON.stringify(row));
      this.reset();
      const id = row.id || this.ids

      getChannel(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改自办节目";
        if(this.form.urlType === "1"){
          this.checkUsbExist();
        }
      });

    },
        // 用户状态修改
        handleStatusChange(row) {
      let text = row.channelStatus === "0" ? "开启" : "关闭";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"频道吗？').then(function() {
        return changeChannelStatus(row.id, row.channelStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.channelStatus = row.channelStatus === "0" ? "1" : "0";
      });
    },


    submitData: function (){
      this.$refs["form"].validate(valid => {
        console.log("============提交校验:"+valid+"=======&&&&&&&&&&==="+JSON.stringify(this.form));
        if (valid) {
          if(this.form.urlType === "1"){
            //U盘
            const checkedNodes = this.$refs.tree.getCheckedNodes();
            console.log("提交信息 checkedNodes : "+JSON.stringify(checkedNodes));
            const filePaths = checkedNodes.map(node => node.path);
            console.log("===================handleNodeClick:"+JSON.stringify(this.selectedNode));
            console.log("提取需要上传的文件信息:"+JSON.stringify(filePaths)+"========"+filePaths.length);
      

            if(filePaths.length == 0){
              this.$modal.msgError("请选择自办节目的源文件");
              return;
            }
            this.openDataScope = false;
            this.form.sourcePaths = filePaths;
            console.log("formData: "+JSON.stringify(filePaths)+"======="+this.form);
            // this.form.sourceUrl = this.selectedNode;
         
          }
          if (this.form.id != null) {
            //修改
            updateChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }else{
            //新增
            addChannel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }




        // console.log("提交数据: "+JSON.stringify(data));
        // axios.post(this.startUploadUrl, data , {
        //   headers: {
        //     'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        //   },
        // }).then(response => {
        //     var code = response.data.code;
        //     console.log("文件上传响应: "+JSON.stringify(response.data)+"==================code:"+code);
        //     if(code == 200){
        //       this.uploadTaskId = response.data.data;
        //       document.body.style.overflow = 'hidden'; // 禁用页面滚动
        //       this.timer = setInterval(() => {
        //         console.log("启动定时器");
        //         this.getUploadProgress();
        //       }, 1000);
        //     }else{
        //         this.$modal.msgError(JSON.stringify(response.data.msg));
        //         this.uploadProgress = -1;
        //     }
        // }).catch(error => {
        //     console.error('上传失败', error);
        //     this.uploadProgress = -1;
        // });
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var boardId = row.boardId;
      console.log("删除:"+boardId);
      if(boardId != -1){
        this.$message.error('非自办节目,不允许进行删除');
        return;
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该自办节目数据项？').then(function() {
        return delChannel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
        /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChannel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
  }

};
</script>
